package com.tensquare.article.service;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.Date;
import java.util.List;
import java.util.Queue;

@Service
public class CommentService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CommentRepository  commentRepository;
    @Autowired
    MongoTemplate mongoTemplate;


    public void save(Comment comment) {
        comment.set_id(idWorker.nextId()+"");
        comment.setPublishdate(new Date());
        comment.setThumbup(0);
        commentRepository.save(comment);
    }

    public void deleteById(String id) {
        commentRepository.deleteById(id);
    }

    public void updateByid(Comment comment) {
        commentRepository.save(comment);
    }

    public List<Comment> findAll() {
        List<Comment> all = commentRepository.findAll();
        return all;
    }

    public Comment findById(String id) {
       return commentRepository.findById(id).get();
    }

    public List<Comment> findByAId(String articleId) {
        List<Comment> list = commentRepository.findByArticleid(articleId);
        return list;
    }
    public void thumbup(String id) {
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update=new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"comment");

    }
}
